'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    errorHandler = require('./errors.server.controller'),
    SynchupsAndSessions = mongoose.model('SynchupsAndSessions'),
    _ = require('lodash');

/**
 * Create a Session
 */
exports.create = function(req, res) {
    //scheduleDate: "2014-12-31T18:30:00.000Z"
    //scheduleTime: "2014-12-27T21:14:51.911Z"

    var session = new SynchupsAndSessions(req.body);
    session.isActive= true;
    session.save(function(err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.json(session);
        }
    });
};

/**
 * Save audience of the session
 */
exports.startSession = function(req, res) {
    var sess = req.sess,selectedAudience=req.body.audience;
    if(_.isArray(selectedAudience) && selectedAudience.length>0){
        sess.startsOn = req.body.startsOn;
        sess.audience = selectedAudience;
    }else{
        sess.audience =[];
    }

    sess.save(function (err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.json(sess);
        }
    });
};

/**
 * Show the current Session
 */
exports.read = function(req, res) {
    res.json(req.sess);
};

/**
 * Session middleware
 */
exports.sessionByID = function(req, res, next, id) {
    SynchupsAndSessions.findById(id).populate('by', 'displayName').exec(function(err, session) {
        if (err) return next(err);
        if (!session) return next(new Error('Failed to load session ' + id));
        req.sess = session;
        next();
    });
};

/**
 * Update a Session
 */
exports.update = function(req, res) {

};

/**
 * Delete an Session
 */
exports.delete = function(req, res) {
    var session =  req.sess;

    // if session is active then deactivate the session
    if(session.isActive){
        session.isActive = false;
        session.save(function(err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.json(session);
            }
        });

    }else{
        // if session is already deactivated the remove this session
        session.remove(function(err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.json(session);
            }
        });
    }
};

/**
 * List of Sessions
 */
exports.list = function(req, res) {
    SynchupsAndSessions.find({}).sort('-scheduledOn').exec(function(err, sessions) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.json(sessions);
        }
    });
};
/**
 * Rate a session
 */
exports.rate = function(req, res) {
    var audienceId = req.user.id,
        audienceRating={},
        presenterId = req.body.presenterId,
        rating=req.body.rating,
        sess = req.sess;
    if(sess.audience.indexOf(audienceId)>0 && _.isNumber(rating)) {
        var presenterToRate = _.find(sess.presenters, function (presenter) {
            return presenter.userId.toString() === presenterId;
        });
        var exisitingRating = _.find(presenterToRate.rating, function (rating) {
            return rating.ratedBy.toString() === audienceId;
        });
        // if no rating is given to presenter the init is with array
        if (_.isUndefined(presenterToRate.rating)) {
            presenterToRate.rating = [];
        }
        // if user is not rated this presenter
        if (_.isUndefined(exisitingRating)) {
            audienceRating = {
                ratedBy: audienceId,
                rating: rating,
                ratedOn: new Date()
            };
            presenterToRate.rating.push(audienceRating);
        } else {
            exisitingRating.rating = rating;
            exisitingRating.ratedOn = new Date();

        }

        sess.save(function (err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.json(sess);
            }
        });
    }else {
        res.json(sess);
    }
};

/**
 * Session authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
    if (req.session.user.id !== req.user.id) {
        return res.status(403).send({
            message: 'User is not authorized'
        });
    }
    next();
};

/**
 * Group Captain or member who created the session can delete the session
 */
exports.userCanUpdateThisSession = function(req, res, next) {
    //if (req.session.user.id !== req.user.id) {
    //    return res.status(403).send({
    //        message: 'User is not authorized'
    //    });
    //}
    next();
};
